from lib.common import CommonResponse
from app001.models import Task
import uuid


def _task_data(task):
    task_id = task.pk
    task_uid = str(task.task_uid)
    task_name = task.task_name
    task_time = str(task.task_time)
    task_desc = task.task_desc
    return {
        'task_id': task_id,
        'task_uid': task_uid,
        'task_name': task_name,
        'task_time': task_time,
        'task_desc': task_desc,
    }


def _verify_tid(tid: str):
    if not tid.isdigit():
        return False
    return True


def get(request):
    data = []
    task_all = Task.objects.all()
    # for task in task_all:
    #     print(task._meta.fields)
    #     task_data = {}
    #     for field in task._meta.fields:
    #         field_name = field.name
    #         field_value = getattr(task, field_name)
    #         task_data.update({field_name: field_value})
    #     data.append(task_data)
    for task in task_all:
        data_dict = _task_data(task)
        data.append(data_dict)

    return CommonResponse(code=100, msg='查询所有成功', task_list=data)


def get_one(request, tid):
    if not _verify_tid(tid):
        return CommonResponse(code=104, msg='请输入数字编号')
    task = Task.objects.filter(pk=tid).first()
    if not task:
        return CommonResponse(code=103, msg='当前任务不存在')
    data = _task_data(task)
    return CommonResponse(code=100, msg='查询成功', task=data)


def _get_data_from_request(data):
    task_name = data.get('task_name')
    task_time = data.get('task_time')
    task_desc = data.get('task_desc')
    return task_name, task_time, task_desc


def add(request):
    data = request.POST
    if not data:
        return CommonResponse(code=101, msg='请使用POST请求')
    task_uid = uuid.uuid4()
    task_name, task_time, task_desc = _get_data_from_request(data)
    if not all([task_name, task_time, task_desc]):
        return CommonResponse(code=102, msg='请补齐参数')
    Task.objects.create(task_uid=task_uid, task_name=task_name, task_time=task_time, task_desc=task_desc)
    return CommonResponse(code=100, msg='添加成功')


def delete(request, tid):
    if not _verify_tid(tid):
        return CommonResponse(code=104, msg='请输入数字编号')
    Task.objects.filter(pk=tid).delete()
    return CommonResponse(code=100, msg='删除任务成功')


def edit(request, tid):
    if not _verify_tid(tid):
        return CommonResponse(code=104, msg='请输入数字编号')
    data = request.POST
    if not data:
        return CommonResponse(code=101, msg='请使用POST请求')
    task_name, task_time, task_desc = _get_data_from_request(data)
    task = Task.objects.filter(pk=tid)
    if not task:
        return CommonResponse(code=103, msg='当前任务不存在')
    task.update(task_name=task_name, task_time=task_time, task_desc=task_desc)
    return CommonResponse(code=100, msg=f'更新任务 {task_name} 成功')
